from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
from web.forms.project import ProjectListModelForm
from web import models
from utils import cos
import time


def project_list(request):
    # 获取用户额度
    form = ProjectListModelForm(request)
    # 获取用户所拥有的项目列表(以下三个)
    """
    用户创建的项目 ： 星标，未星标
    用户参与的项目： 性标，未星标
    所有星标的项目:
    """
    # 定义一个项目字典 存放 星标、创建、参与的项目列表
    project_dict = {'star': [], 'my': [], 'join': []}
    # 1.获取用户创建的所有项目
    my_project_list = models.Project.objects.filter(creator=request.tracer.user)
    for row in my_project_list:
        # 将星表的项目 存到字典的star列表中,其他存放到 参与的项目中
        if row.star:
            project_dict['star'].append({'type': 'my', 'value': row})
            # 用来区分星表里的时创建的还是参与的项目
        else:
            project_dict['my'].append(row)
    # 2. 获取用户所参与的项目
    join_project_list = models.ProjectUser.objects.filter(user=request.tracer.user)
    for item in join_project_list:
        if item.star:
            project_dict['star'].append({'type': 'join', 'value': item.project})
        else:
            project_dict['join'].append(item.project)

    """POST 请求创建项目"""
    if request.method == 'POST':
        form = ProjectListModelForm(request, data=request.POST)
        # 验证表单
        if form.is_valid():
            # 定义一个 cos桶名，要求唯一,这里以手机号-时间戳-数字
            bucket = "{}-{}-1305478366".format(request.tracer.user.mobile_phone, str(int(time.time())))
            region = "ap-shanghai"
            # 1 调用写好的方法创建cos桶
            cos.create_cos_bucket(bucket, region)
            # 2.写入数据库,用户，bucket，region,创建项目
            form.instance.bucket = bucket
            form.instance.region = region
            form.instance.creator = request.tracer.user
            project_object = form.save()
            # 3.为项目初始化问题类型,(插入问题类型表数据)
            issues_type_obj_list=[]
            for item in models.IssuesType.issues_type_list:
                issues_type_obj_list.append(models.IssuesType(title=item,project=project_object))
            # 批量创建表数据
            models.IssuesType.objects.bulk_create(issues_type_obj_list)
            return JsonResponse({'status': True})
        else:
            return JsonResponse({'status': False, 'error': form.errors})
    return render(request, 'project_list.html', {'form': form, 'project_dict': project_dict})


def project_star(request, project_type, project_id):
    """点击项目标注星标"""
    # 根据传来的项目类型 获取项目对象 修改star 为True
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=True)
        return redirect('project_list')
    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=True)
        return redirect('project_list')
    return HttpResponse('访问出错')


def project_unstar(request, project_type, project_id):
    """点击取消星标"""
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=False)
        return redirect('project_list')
    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=False)
        return redirect('project_list')
    return HttpResponse('访问出错')
